<template>
  <div>
    <tableComponents
      :pagination="{ currentPage, pageSize, total: list.all_num }"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      exportUrl="/api/admin/export/bd_msg"
      @toExport="toExport"
      @toAdd="editForm"
      :isHaveAdd="false"
    >
      <template v-slot:search>
        <bdMsgSearch
          @sendSearch="getSearch"
          @sendMoney="getMoney"
        ></bdMsgSearch>
      </template>
      <template v-slot:table>
        <el-table
          v-loading="loading"
          ref="multipleTable"
          :data="list.data"
          stripe
          header-row-class-name="head_color"
          tooltip-effect="dark"
          style="width: 99.8%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            class="tc"
            width="35"
          ></el-table-column>
          <el-table-column label="头像" min-width="50">
            <template slot-scope="scope">
              <div class="img_bor_tx">
                <img :src="$fnc.getImgUrl(scope.row.avatar)" alt />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="用户信息" min-width="120">
            <template slot-scope="scope">
              <div class="tab_div">
                <div>
                  <span>用户昵称：</span>
                  <span>{{ scope.row.nickname || "----" }}</span>
                </div>
                <div>
                  <span>会员账号：</span>
                  <span
                    @click="func_1(scope.row.uid)"
                    style="cursor: pointer"
                    >{{ scope.row.username }}</span
                  >
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="订单" min-width="120">
            <template slot-scope="scope">
              <div class="tab_div">
                <div>
                  <span>订单号：</span>
                  <span>{{ scope.row.oid || "----" }}</span>
                </div>
                <div
                  v-if="
                    scope.row.oid != '' &&
                    scope.row.oid != null &&
                    scope.row.oid != undefined
                  "
                >
                  <div>
                    <span>是否支付：</span>
                    <span>{{
                      scope.row.is_pay == 1 ? "已支付" : "未支付"
                    }}</span>
                  </div>
                  <div v-show="scope.row.is_pay == 1">
                    <span>支付方式：</span>
                    <span>{{ scope.row.pay }}</span>
                  </div>
                  <div v-show="scope.row.is_pay == 1">
                    <span>支付时间：</span>
                    <span>{{ scope.row.pay_time | getTimeFormat }}</span>
                  </div>
                </div>
                <div>
                  <span>时间：</span>
                  <span>{{ scope.row.created_time | getTimeFormat }}</span>
                </div>
                <div>
                  <span>备注：</span>
                  <span>{{ scope.row.remark || "----" }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="是否审核" min-width="80">
            <template slot-scope="scope">
              <el-switch
                class="zdySwith"
                :width="82"
                v-model="scope.row.is_check"
                active-color="#1aad19"
                inactive-color="#ffffff"
                active-text="已审核"
                inactive-text="未审核"
                active-value="1"
                @change="checkSh($event, scope.row)"
                inactive-value="0"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="字段值">
            <template slot-scope="scope">
              <div class="tab_div" v-if="scope.row.tel || scope.row.vaule">
                <div>
                  <span>联系方式：</span>
                  <span>{{ scope.row.tel || "----" }}</span>
                </div>
                <div>
                  <span>选项内容：</span>
                  <span>{{ scope.row.vaule || "----" }}</span>
                </div>
              </div>
              <div class="tab_div">
                <div v-for="(item, i) in tabHead" :key="i">
                  <span style="vertical-align: top">{{ item.title }}：</span>
                  <span v-if="toType(item.iden) == '5'">{{
                    scope.row[item.iden] | getTimeFormat
                  }}</span>
                  <span v-else-if="toType(item.iden) == '6'">
                    <el-popover
                      placement="right"
                      title
                      trigger="hover"
                      :key="k"
                      v-for="(img, k) in toZimg(scope.row[item.iden])"
                    >
                      <el-image
                        :src="img"
                        :preview-src-list="srcList"
                      ></el-image>
                      <el-image
                        slot="reference"
                        style="width: 30px; height: 30px; margin: 0 5px 5px 0"
                        :src="img"
                        :preview-src-list="srcList"
                      >
                      </el-image>
                    </el-popover>
                  </span>
                  <span v-else>{{ scope.row[item.iden] || "---" }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" min-width="120">
            <template slot-scope="scope">
              <el-button
                :loading="$store.state.isLoading"
                size="mini"
                type="danger"
                @click="checkBd(scope.row, scope.$index)"
                >修改备注</el-button
              >
              <el-button
                :loading="$store.state.isLoading"
                size="mini"
                type="primary"
                @click="editForm(scope.row, scope.$index)"
                >编辑</el-button
              >
              <el-button
                :loading="$store.state.isLoading"
                size="mini"
                @click="deleteNew(scope.$index, scope.row.id)"
                type="danger"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-slot:footerLeft>
        <a class="aBtn aBtn_1 aBtn_lan2" @click="deleteLises">删除</a>
      </template>
    </tableComponents>

    <el-dialog
      title="修改备注"
      :close-on-click-modal="false"
      class="tl size_13"
      :append-to-body="true"
      :visible.sync="showBdMsg"
      width="800px"
    >
      <el-form :model="form" ref="form" label-width="120px">
        <!-- <el-form-item label="是否审核" prop="is_open">
        <el-col :span="12" class="tl">
          <el-switch
            class="zdySwith"
            :width="82"
            v-model="form.is_check"
            active-color="#1aad19"
            inactive-color="#ffffff"
            active-text="已审核"
            inactive-text="未审核"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </el-col>
        </el-form-item>-->

        <el-form-item label="备注">
          <el-col :span="12">
            <el-input v-model="form.remark" type="textarea"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="编辑表单"
      :close-on-click-modal="false"
      class="tl size_13"
      :append-to-body="true"
      :visible.sync="add_show"
      width="800px"
      @close="closeField"
    >
      <el-form ref="form" label-width="120px">
        <el-form-item label="关联用户">
          <el-col :span="9">
            <el-input
              placeholder="请选择用户"
              v-model="field.username"
              :disabled="true"
            ></el-input>
          </el-col>
          <el-button
            :loading="$store.state.isLoading"
            size="small"
            type="primary"
            @click="xzshop()"
            style="margin-left: 10px"
          >
            选择
          </el-button>
        </el-form-item>
        <el-form-item
          :label="item.title"
          v-for="(item, i) in fields.field"
          :key="i"
        >
          <!-- <el-col :span="16"> -->
          <div v-if="item.types == '1' || item.types == '7'">
            <el-col :span="12">
              <el-input
                v-model="field[item.iden]"
                :type="item.types == 7 ? 'textarea' : 'text'"
              ></el-input>
            </el-col>
          </div>

          <div v-if="item.types == '2'">
            <el-col :span="12">
              <el-radio-group v-model="field[item.iden]">
                <el-radio
                  v-for="(itemS, indexS) in toZhuan(item.parameter)"
                  :key="indexS"
                  :label="itemS"
                ></el-radio>
              </el-radio-group>
            </el-col>
          </div>

          <div v-if="item.types == '3'">
            <el-col :span="12">
              <el-checkbox-group v-model="field[item.iden]">
                <el-checkbox
                  v-for="(itemS, indexS) in toZhuan(item.parameter)"
                  :key="itemS[indexS]"
                  :label="itemS"
                  >{{ itemS }}</el-checkbox
                >
              </el-checkbox-group>
            </el-col>
          </div>

          <div v-if="item.types == '4'">
            <el-col :span="12">
              <el-select v-model="field[item.iden]" placeholder="请选择">
                <el-option
                  v-for="(ItemS, IndexS) in toZhuan(item.parameter)"
                  :key="ItemS[IndexS]"
                  :label="ItemS"
                  :value="ItemS"
                ></el-option>
              </el-select>
            </el-col>
          </div>

          <div v-if="item.types == '5'">
            <el-col :span="12">
              <el-date-picker
                style="width: 310px"
                size="large"
                v-model="field[item.iden]"
                type="datetime"
                placeholder="选择时间"
              ></el-date-picker>
            </el-col>
          </div>

          <div v-if="item.types == '6'">
            <el-col :span="12">
              <el-input
                v-model="field[item.iden]"
                autocomplete="off"
                class="mar_bottom_5"
              ></el-input>
              <uploadpic
                :index="i"
                :piclink="field[item.iden]"
                :width="150"
                :height="150"
                :is_more="false"
                @send_pic="getSuccess($event, item, i)"
              ></uploadpic>
            </el-col>
          </div>

          <div v-if="item.types == '8'">
            <el-col :span="12">
              <city-cascader
                :level="3"
                :checkStrictly="true"
                @change="handleItemChange($event, item, i)"
              />
            </el-col>
          </div>
          <!-- </el-col> -->
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="subField">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <keep-alive>
      <component
        :is="'xzuser'"
        :show="show_xzuser"
        :isAll="false"
        :isPart="true"
        showType="list"
        @sendShop="getSend"
        @isshow="getShow"
      ></component>
    </keep-alive>
  </div>
</template>
<script>
import bdMsgSearch from "./bd-msg-search";
import uploadpic from "@/components/page/pic/up_pic";
import cityCascader from "@/components/currency/cityCascader/cityCascader";
import { mapState } from "vuex";
import xzuser from "@/components/currency/xz_user.vue";
export default {
  components: {
    bdMsgSearch,
    uploadpic,
    cityCascader,
    xzuser,
  },
  data() {
    return {
      srcList: [],
      loading: false,
      list: [],
      allPage: 0,
      allNum: 0,
      pageSize: 10,
      currentPage: 1,
      searchAll: {
        username: "",
      },
      item: {
        cate: "",
      },
      tabHead: [],
      multipleSelection: [],
      form: {
        id: "",
        remark: "",
        is_check: "",
        bid: "",
      },
      index: -1,
      showBdMsg: false,
      fields: {}, //表单对象
      add_show: false, //添加表单
      field: {},
      fid: "", //表单id
      show_xzuser: false,
    };
  },

  methods: {
    getInfo () {
      this.$api.getForm.getBdList().then((res) => {
        if (res.data.code == 200) {
          this.$store.commit("setPluginForm", res.data.result);
          var params = this.searchAll;
          this.page = this.$route.query.page || 1;
          params.page = this.$route.query.page || 1;
          params.page_size = this.pageSize;
          params.oid = this.oid;
          this.getNewsAll(params);
          this.currentPage = Number(this.$route.query.page) || 1;
        }
      });
    },
    getShow(val) {
      this.show_xzuser = val;
    },
    getSend(row) {
      this.field.username = row.username;
      this.field.uid = row.id;
    },
    xzshop() {
      this.show_xzuser = true;
    },
    toExport(str) {
      if (str) {
        var params = JSON.parse(JSON.stringify(this.searchAll));
        this.$fnc.postExcelFile(params, str);
      } else {
        this.$fnc.alertError("请检查地址", str);
      }
    },
    toZimg(imgStr) {
      if (imgStr) {
        return imgStr.split("@");
      } else {
        return [];
      }
    },
    toType(iden) {
      console.log(iden);
      var arr = this.tabHead;
      for (var i in arr) {
        if (arr[i].iden == iden) {
          return arr[i].types;
        }
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var params = {};
          params = this.form;
          if (params.id) {
            this.$api.getForm.saveEditBdMsg(params).then((res) => {
              if (res.data.status == 1 && res.data.code == 200) {
                this.showBdMsg = false;
                this.list.data[this.index].remark = params.remark;
                this.$swal("修改成功！", res.data.result, "success");
              } else {
                this.$fnc.alertError(res.data.code_desc, res.data.result);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    checkBd(row, index) {
      this.form.id = row.id;
      this.form.remark = row.remark;
      this.form.bid = row.bid;
      this.form.is_check = row.is_check;
      this.showBdMsg = true;
      this.index = index;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    checkSh(val, row) {
      var params = {};
      params.id = row.id;
      params.bid = row.bid;
      params.is_check = val; //saveEditBdMsg
      this.$api.getForm.saveEditBdMsg(params).then((res) => {
        if (res.data.status == 1 && res.data.code == 200) {
          //  this.$message.success('提交成功');
        } else {
          this.$fnc.alertError(res.data.code_desc, res.data.result);
        }
      });
    },
    deleteLises() {
      //批量删除
      var str = "";
      if (this.multipleSelection.length <= 0) {
        this.$message.error("未选择批量删除");
      } else {
        for (var i in this.multipleSelection) {
          str += this.multipleSelection[i].id + "@";
        }
        str = str.slice(0, -1);
        this.$swal({
          title: "您确定要删除这些信息吗",
          text: "删除后将无法恢复，请谨慎操作！",
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "是的，我要删除",
          cancelButtonText: "容我三思",
        }).then((willDelete) => {
          if (willDelete.value) {
            var data = { id_str: str };
            data.bid = this.searchAll.id;
            this.$api.getForm.delBdMsg(data).then((res) => {
              if (res.data.code == 200) {
                this.$swal("删除成功！", "您已经删除了这些信息。", "success");
                this.getNewsAll("", this.pageSize);
              } else {
                this.$swal("删除失败！", res.data.result, "success");
              }
            });
          }
        });
      }
    },
    deleteNew(index, id) {
      this.$swal({
        title: "您确定要删除这条信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "是的，我要删除",
        cancelButtonText: "容我三思",
      }).then((willDelete) => {
        if (willDelete.value) {
          var data = { id_str: id };
          data.bid = this.searchAll.id;
          this.$api.getForm.delBdMsg(data).then((res) => {
            if (res.data.code == 200) {
              this.$swal("删除成功！", "您已经删除了这条信息。", "success");
              this.list.data.splice(index, 1);
            } else {
              this.$swal("删除失败！", res.data.result, "success");
            }
          });
        }
      });
    },
    getSearch(obj) {
      for (var i in this.item) {
        obj[i] = this.item[i];
      }
      this.searchAll = obj;
      this.$router.push(
        this.$route.path + "?page=" + 1 + "&id=" + this.searchAll.id
      );

      this.getNewsAll(obj);
    },
    getMoney(obj) {
      this.item = obj;
      for (var i in this.item) {
        obj[i] = this.item[i];
      }

      this.searchAll = obj;
      this.$router.push(
        this.$route.path + "?page=" + 1 + "&id=" + this.searchAll.id
      );
      this.getNewsAll(this.searchAll);
    },
    getNewsAll(data) {
      this.loading = true;
      var params = {};
      data = data || {};
      params = data;
      try {
        if (!params.id) {
          params.id = this.$route.query.id || this.formLists[0].id || "";
        }
      } catch (error) {
        this.$message.error("请先创建表");
        return;
      }

      params.oid = this.oid || data.oid || "";
      this.$api.getForm.getBdMsgLists(params).then((res) => {
        if (res.data.code == 200) {
          this.list = res.data.result;
          this.tabHead = res.data.result.field;
        }
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      var params = this.searchAll;
      params.page = "";
      params.page_size = val;
      this.getNewsAll(params);
      this.pageSize = val;

      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      // console.log(`当前页:`+val)

      this.currentPage = parseInt(val);
      var params = this.searchAll;
      params.page = val;
      params.page_size = this.pageSize;
      this.getNewsAll(params);
    },

    func_1(val) {
      let routeData = this.$router.resolve({
        path: "/index/user/user_info",
        query: { id: val },
      });
      window.open(routeData.href, "_blank");
    },
    editForm(form, index) {
      // 打开添加
      this.fid = this.$route.query.id || this.formLists[0].id || "";
      var params = {};
      params.id = this.fid;
      this.$api.getForm.getFieldForm(params).then((res) => {
        if (res.data.code == 200) {
          this.fields = res.data.result;
          this.add_show = true;
        } else {
          this.$fnc.alertError(res.data.result);
        }
      });
      if (form) {
        this.field = form;
        this.add_show = true;
      }
    },
    toZhuan(str) {
      //字符串转数组
      if (str == "") {
        return [];
      } else {
        return str.split("@");
      }
    },
    getSuccess(pic, item, index) {
      //上传图片
      this.field[item.iden] = pic;
    },
    handleItemChange(val, item, index) {
      // 选择地址
      this.field[item.iden] = val.join("");
    },
    subField() {
      //保存 添加表单
      var params = this.field;
      if (this.field.bid) {
        this.$api.getForm.editFieldForm(params).then((res) => {
          if (res.data.code == 200) {
            this.$fnc.alertSuccess("修改成功");
            this.add_show = false;
            this.getNewsAll("", this.pageSize);
          } else {
            this.$fnc.alertError(res.data.result);
          }
        });
      } else {
        this.$confirm("是否确认提交?", "提交", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            params.id = this.fid;
            console.log("eeeeeeeeeeeeeeeeeee:", params);
            this.$api.getForm.addFieldForm(params).then((res) => {
              if (res.data.code == 200) {
                this.$fnc.alertSuccess("提交成功");
                this.add_show = false;
                this.getNewsAll("", this.pageSize);
              } else {
                this.$fnc.alertError(res.data.result);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      }
    },
    closeField() {
      this.field = {};
    },
  },
  watch: {
    $route() {
      // var params = this.searchAll;
      // params.page = this.$route.query.page || 1;
      // params.page_size = this.pageSize;
      // this.getNewsAll(params);
      // this.currentPage = Number(this.$route.query.page) || 1;
    },
  },
  beforeCreate() {
    var page = this.$route.query.page || 1;
    var str = "";
    if (this.$route.query.id) {
      str = "&id=" + this.$route.query.id;
    }
    this.$router.push(this.$route.path + "?page=" + page + str);
  },
  created() {
    this.getInfo();
  },
  filters: {
    toFixedTwo(val) {
      var num = val.indexOf(".");

      return val.substring(0, num + 4);
    },
  },
  computed: {
    ...mapState({
      formLists: (state) => state.formList,
    }),
  },
};
</script>

<style scoped>
.recharge_sum {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
  padding-left: 10px;
}
.recharge_sum p {
  font-size: 14px;
  line-height: 32px;
  padding-right: 50px;
  text-align: left;
}
.recharge_sum span {
  font-size: 14px;
  font-weight: bold;
}
</style>
